package com.lagou.edu.controller;

import com.lagou.edu.pojo.User;
import com.lagou.edu.service.LoginService;
import com.lagou.edu.service.ServiceApi;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/user")
public class LoginController {
//    @Autowired
//    private ResumeServiceFeignClient resumeServiceFeignClient;
    @Reference(timeout = 3000)
    ServiceApi serviceApi;

    @Autowired
    LoginService loginService;

    @Resource(name = "redisStringTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/skip")
    public String findResumeOpenState() {
        return "login";
    }

    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    @RequestMapping("/addUser")
    @ResponseBody
    public String addUser(HttpServletRequest request, HttpServletResponse response, User user) {
        String strKey =  request.getSession().getId();

        if(redisTemplate.hasKey("code" + strKey)){
            String code = redisTemplate.opsForValue().get("code" + strKey).toString();
            if (code.equals(user.getToken())){
                loginService.insertUser(user);
                return "0";
            }
        }

        return "2";
    }

    @RequestMapping("/code")
    @ResponseBody
    public String code(HttpServletRequest request, HttpServletResponse response) {
        String s = generateWord();
        serviceApi.sendEmail(s);
        System.err.println("验证码："+s);
        String strKey =  request.getSession().getId();
        redisTemplate.opsForValue().set("code"+strKey,s,60,TimeUnit.SECONDS);
        return s;
    }

    @RequestMapping("/welcome")
    public String welcome() {
        return "welcome";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(HttpServletRequest request, HttpServletResponse response, User user) throws Exception {
        User queryUser = loginService.queryUser(user);
        if (queryUser!= null) {
            Cookie[] cookies = request.getCookies();
            String sessionId = request.getSession().getId();
            Cookie cookie = findCookie(cookies, "token");
            if (cookie == null) {
                response.addCookie(new Cookie("token", request.getSession().getId()));
            } else {
                cookie.setValue(request.getSession().getId());
            }
            redisTemplate.opsForValue().set(sessionId,user.getUsername(),30*60*1000, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set("user", user.getUsername(),30*60*1000, TimeUnit.SECONDS);
            System.err.println("sessionId: "+sessionId);
            queryUser.setToken(request.getSession().getId());
            loginService.saveToken(queryUser);
            return "login";
        }
        return "false";
    }




    public Cookie findCookie(Cookie[] cookies, String name) {
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }
        return null;
    }

    private String generateWord() {  
        String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7",  
            "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",  
            "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",  
            "W", "X", "Y", "Z" };  
        List list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();  
        for (int i = 0; i < list.size(); i++) {  
            sb.append(list.get(i));  
        }  
        String afterShuffle = sb.toString();  
        String result = afterShuffle.substring(5, 9);  
        return result;  
    }  
}